import React from 'react'
import { Route, Redirect, withRouter } from 'react-router-dom'
import PropTypes from 'prop-types'
import {
  inject,
  observer,
} from 'mobx-react'

import TopicList from '../views/topic-list/index'
import TopicDetail from '../views/topic-detail/index'
import ApiTest from '../views/test/api-test'
import UserLogin from '../views/user/login'
import UserInfo from '../views/user/info'

// 路由拦截
const PrivateRoute = ({ isLogin, component: Component, ...rest }) => (
  <Route
    {...rest}
    render={
      props => (
        isLogin ?
          <Component {...props} /> :
          <Redirect
            to={{
              pathname: '/user/login',
            }}
          />
      )
    }
  />
)

const IsNeedLoginRoute = withRouter(inject(({ appState }) => ({
  isLogin: appState.user.isLogin,
}))(observer(PrivateRoute)))

PrivateRoute.propTypes = {
  isLogin: PropTypes.bool,
  component: PropTypes.element.isRequired,
}

PrivateRoute.defaultProps = {
  isLogin: false,
}

export default () => [
  <Route path="/" render={() => <Redirect to="/list" />} exact key="/" />,
  <Route path="/list" component={TopicList} key="/list" />,
  <Route path="/detail/:id" component={TopicDetail} key="/detail" />,
  <Route path="/test" component={ApiTest} key="/test" />,
  <Route path="/user/login" component={UserLogin} key="/user/login" />,
  <IsNeedLoginRoute path="/user/info" component={UserInfo} key="/user/info" />,
]
